<template>
    <div class="main">
        <!-- 1.0 面包屑 -->
        <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/layout' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb> -->
        <!-- 抽离了面包屑组件 -->
        <crumbs-nav :level1="'用户管理'" :level2="'用户列表'"></crumbs-nav>
        <!-- 2.0 搜索框和添加按钮 -->
        <div class="search">
            <el-input placeholder="请输入内容" v-model="query" class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="getUserListDate"></el-button>
            </el-input> 
            <el-button style='margin-left:5px;' type="success" plain  @click="dialogVisibleadd = true">添加用户</el-button> 
        </div>
        <!-- 3.0 表格 -->
        <template>
          <el-table
            :data="tableUserData"
            border
            style="width: 100%">
                <el-table-column
                  type='index'
                  label="序号"
                  width="50">
                </el-table-column>

                <el-table-column
                  prop="username"
                  label="姓名"
                  width="180">
                </el-table-column>

                <el-table-column
                  prop="email"
                  label="邮箱">
                </el-table-column>

                <el-table-column
                  prop="role_name"
                  label="角色">
                </el-table-column>

                <el-table-column
                  prop="mobile"
                  label="电话">
                </el-table-column>

                 <el-table-column
                    prop="mg_state"
                    label="用户状态"
                    width="180">
                    <template slot-scope="scope">
                        <el-switch
                            @change="switchChange(scope.row.id,scope.row.mg_state)"
                            v-model="scope.row.mg_state">
                        </el-switch>
                    </template>
                </el-table-column>

                <el-table-column 
                min-width='250'
                label="操作">
                    <template slot-scope="scope">
                        <el-button
                        size="mini"
                        type="primary"
                        @click="handleClickEdit(scope.row)"
                        plain><i class="el-icon-edit"></i>   
                        <!-- 编辑 -->
                        </el-button>
                        
                        <!-- 删除 -->  
                        <el-button 
                        size="mini" 
                        type="warning" 
                        plain 
                        @click="handleClickDelete(scope.row)"><i class="el-icon-delete"></i>
                        </el-button>
                        
                        
                        <el-button
                        size="mini"
                        type="warning"
                         @click="handleClickAddRole(scope.row)"
                        plain><i class="el-icon-check"></i>
                        </el-button>
                    </template>
                </el-table-column>
          </el-table>
            <!-- 4.0分页 -->
          <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pagenum"
                :page-sizes="[5, 10, 20]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
          </el-pagination>
        </template>

        <!-- 5.0添加弹框 -->
        <el-dialog
            title="新增用户"
            :visible.sync="dialogVisibleadd"
            width="50%"
            >
            
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"  class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="ruleForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="ruleForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="ruleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                  <el-input v-model="ruleForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisibleadd = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 6.0更改弹框 -->
        <el-dialog
            title="修改用户信息"
            :visible.sync="dialogVisibleedit"
            width="50%"
            >
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"  class="demo-ruleForm">
                <el-form-item  label="用户名" prop="username">
                  <el-input style="width:100px" disabled v-model="ruleForm.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="ruleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                  <el-input v-model="ruleForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisibleedit = false">取 消</el-button>
              <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
  
        <el-dialog
                title="提示"
                :visible.sync="dialogVisibleAddRole"
                width="30%">
                <!-- 表单模板 -->
                <template>
                    <el-form ref="editRole"  label-width="80px">
                        <el-form-item label="角色名称">
                          <!-- select模板 -->
                            <template>
                                <el-select @change="selectChange"  v-model="roleName" ref="editRoleSelect" :placeholder="roleName" >
                                    <el-option
                                      v-for="item in roleList"
                                      :key="item.id"
                                      :value="item.roleName">
                                    </el-option>                              
                                </el-select>                            
                            </template>
                        </el-form-item>
                    </el-form>
                </template> 
              
                <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogVisibleAddRole = false">取 消</el-button>
                  <el-button type="primary" @click="handleClickSendAddRole">确 定</el-button>
                </span>
            </el-dialog>
         
    </div>
</template>

<script>
import crumbsNav from '../../common/crumbsNav'
export default {
    name: 'UserList',
    components:{
        crumbsNav
    },
     data() {
      return {      
        query:'',       
        pagenum:1,
        pagesize:5,
        total:0,
        tableUserData: [],
        dialogVisibleadd:false,
        dialogVisibleedit:false,
        dialogVisibleAddRole:false,
        ruleForm:{
            username:'',
            password:'',
            email:'',
            mobile:''
        },
        roleList:[],
        roleMsg:{
               id:'',
               roleName:'',
               roleDesc:''
           },
        userId:'',
        roleId:null,
        roleName:'',
         rules: {
            username: [
                { required: true, message: '请输入用户名', trigger: 'blur' },
                { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'blur' },
                { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
            ]
         }
      }
    },
    created(){
        this.getUserListDate()
    },
    methods:{
        //修改角色
        // handleClickAddRole(scope){

        // },
    
         handleClickAddRole(val){
             console.log(val);
             this.userId = val.id
             this.roleName = val.role_name
            this.dialogVisibleAddRole = true 
            // console.log(this.$refs.editRoleSelect)
             this.$axios.get(`roles`).then(res => {
                 console.log(1111);
                
               console.log(res.data.data)
               this.roleList = res.data.data
               console.log(this.roleList)
           })
           
        },  
        selectChange(roleId){
            console.log(roleId)
            this.roleList.forEach(item =>{
                if(item.roleName==roleId){
                    
                    this.roleId = item.id
                    console.log(typeof (this.roleId))
                }
            })
            // this.roleId = roleId
        },
        //提交修改
        handleClickSendAddRole(){
            
            if(this.$refs.editRoleSelect.value){
                console.log(1111)
                this.$axios.put(`users/${this.userId}/role`,{
                    
                        rid:this.roleId
                    
                })
                .then(res => {
                    console.log(res.data)
                    this.dialogVisibleAddRole = false 
                    if(res.data.meta.status==200){
                         this.$message({
                          message: res.data.meta.msg,
                          type: 'success'
                        });
                        console.log(res.data)
                        this.getUserListDate()
                    }
                })
            }else{
                this.$message({
                          message: '请将信息填写完整',
                          type: 'warning'
                 });
            }            
        },
        // 滑块按钮的值改变事件
        switchChange(id,state){
            this.$axios.put(`users/${id}/state/${state}`,{
                params:{
                    id:id
                }             
            }).then(res => {
                console.log(res)
                if(state){
                    this.$message({
                        type: 'success',
                        message: '开启用户'
                    })
                }else{
                    this.$message({
                        type: 'success',
                        message: '禁用用户'
                    })
                }
            })
        },
        // 删除用户
        handleClickDelete(val){    
            this.userId = val.id       
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
                this.$axios.delete(`users/${this.userId}`,{
                    params:{
                        id:this.userId
                    }
                })
                    .then(res => {
                        this.$message({
                        type: 'success',
                        message: res.data.meta.msg
                        });
                        this.getUserListDate()
                    })             
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
                });          
            });
        },
        // 修改用户信息
        handleClickEdit(val){
            this.dialogVisibleedit = true
            this.ruleForm = val
            this.userId = val.id
        },
        // 编辑用户信息
        editUser(){          
            this.$axios.put(`users/${this.userId}`,this.ruleForm
            ).then(res => {
                if(res.data.meta.status==200){
                    // 让弹框隐藏
                    this.dialogVisibleedit = false;
                    //刷新页面
                    this.getUserListDate()
                }
            })
        },
        // 添加用户
        addUser(){
            this.$axios.post('users',this.ruleForm,{
                headers:{
                    Authorization: localStorage.getItem('myToken')
                }
            })
                .then(res => {
                    this.dialogVisibleadd = false
                    if(res.data.meta.status==201){
                        //添加成功
                        this.$message({
                          type: 'success',
                          message: res.data.meta.msg
                        })
                        this.getUserListDate()
                    }
                })
        },
        // 分页的页面显示数量大小的改变触发的事件
        handleSizeChange(val){
            this.pagesize =val
            this.getUserListDate()
        },
        // 分页的当前页改变触发的事件
        handleCurrentChange(val){
            this.pagenum = val
            this.getUserListDate()
        },
        // 请求用户列表
        getUserListDate(){
            this.$axios.get('users',{
                params:{
                    pagenum:this.pagenum,
                    pagesize:this.pagesize,
                    query:this.query
                },
          
            })
                .then(res => {
                    console.log(res.data.data)
                    this.total = res.data.data.total
                    this.tableUserData = res.data.data.users 
                })
        }
    }
}
</script>

<style scoped>
    .main{
        height: 100%
    }
    .search>.el-input {
        width: 350px;
  }
</style>
